#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

#include "cmdrvfile.h"
#include "armsdkerr.h"

INT4 cmdrv_fd = 0;
BOOL cmdrv_state = FALSE;

INT4 fileOpen(const CHR *filename)
{
    /* 打开驱动 */
    cmdrv_fd = open(filename, O_RDWR);
    if(cmdrv_fd < 0)
    {
        printf("file %s open failed!\r\n", filename);
        return FAILURE;
    }

    cmdrv_state = TRUE;
    return cmdrv_fd;
}

INT4 fileWrite(const CHR *data)
{
    INT4 i4Ret;

    /* 向/dev/{dev}文件写入数据 */
    i4Ret = write(cmdrv_fd, data, sizeof(UINT1));
    if(i4Ret < 0)
    {
        printf("driver Write Failed!\r\n");
        close(cmdrv_fd);
        return FAILURE;
    }

    return SUCCESS;
}

INT4 fileRead(UINT1 *data, INT4 len)
{
    INT4 i4Ret;

    /* 从/dev/{dev}文件读取数据 */
    i4Ret = read(cmdrv_fd, data, len);
    if(i4Ret < 0)
    {
        printf("driver Read Failed!\r\n");
        close(cmdrv_fd);
        return FAILURE;
    }

    return SUCCESS;
}

INT4 fileClose(const CHR *filename)
{
    INT4 i4Ret;

    i4Ret = close(cmdrv_fd); /* 关闭文件 */
    if(i4Ret < 0)
    {
        printf("file %s close failed!\r\n", filename);
        return FAILURE;
    }

    cmdrv_state = FALSE;
    return SUCCESS;
}

INT4 fileState()
{
    return cmdrv_state;
}


